import 'package:flutter/material.dart';
import 'package:hao_ke/consts/consts.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:hao_ke/utils/order_state_util.dart';

import '../../consts/url_const.dart';
import '../../utils/dio_http.dart';
import '../auth/auth.dart';
import '../utils/scoped_model_helper.dart';

class RoomDetails extends StatefulWidget {

  final String? roomId;

  const RoomDetails(this.roomId, {super.key});

  @override
  State createState() {
    return _RoomDetailsState();
  }
}

class _RoomDetailsState extends State<RoomDetails> {

  List<Widget> orderInfos = [];

  String state = '';

  String btnText = '';

  String uno = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('${widget.roomId}'),
        ),
        body: Container(
          padding: const EdgeInsets.all(15),
          decoration: const BoxDecoration(
              gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color.fromRGBO(200, 100, 100, 0.5),
                Color.fromRGBO(0, 0, 200, 0.5),
              ]
          )
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                    boxShadow: const [BoxShadow(
                        color: Colors.grey,
                        offset: Offset(0, 1),
                        blurRadius: 10,
                        blurStyle: BlurStyle.outer
                    )],
                    color: const Color.fromRGBO(200, 200, 200, 0.3),
                    borderRadius: BorderRadius.circular(10)
                ),
                height: 600,
                child: ListView(
                  children: orderInfos,
                ),
              ),
              const SizedBox(height: 10),
              SizedBox(
                width: 50,
                height: 60,
                child: _getButton(),
              )
            ],
          ),
        )
    );
  }

  @override
  void initState() {

    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInfo();
    });
  }

  _getButton() {
    if(state=='2') {
      return Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            FilledButton(
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Color.fromRGBO(50, 150, 100, 0.1)),
                    shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        )
                    )
                ),
                child: Text('开始服务',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.green[500]),),
                onPressed: () {
                  _start_service();
                }
            ),
            FilledButton(
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Color.fromRGBO(50, 150, 200, 0.2)),
                    shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        )
                    )
                ),
                child: Text('取消预约',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.red[300]),),
                onPressed: () {
                  _cancel_service();
                }
            ),
          ]
        )
      );
    }
    return FilledButton(
      style: ButtonStyle(
        shape: MaterialStateProperty.all(
            RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            )
        ),
        backgroundColor: MaterialStateProperty.all(const Color.fromRGBO(200, 200, 200, 0.3)),
      ),
      onPressed: () {
        if(state=='5') {
          // 完成服务/oms/order/admin-over-service?orderNo=UNOD2401161033347751&markFrom=1
          _over_service();
        }
      },
      child: Text(btnText,style: const TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.blue),),
    );
  }

  _over_service () async {
    var res = await DioHttp().init(context, ScopedModelHelper.getModel<AuthModel>(context).token).put("${UrlConst.over_service}?orderNo=$uno&markFrom=1");
    TDToast.showText('服务已经完成', context: context);
  }

  _start_service() async{
    await DioHttp().init(context, ScopedModelHelper.getModel<AuthModel>(context).token).put(UrlConst.start_service+uno);
    TDToast.showText('服务已经开始', context: context);
    getInfo();
  }

  _cancel_service() async{
    await DioHttp().init(context, ScopedModelHelper.getModel<AuthModel>(context).token).delete(
        UrlConst.cancel_service,
        params: {
          'uno': uno,
          'pkid': uno,
          'state': state,
          'isSend': '0',
          'isSendEmployee': '0',
        }
    );
    TDToast.showText('服务已经取消', context: context);
    getInfo();
    Navigator.pop(context);
  }

  getInfo () async{
    var response = await DioHttp().init(context, ScopedModelHelper.getModel<AuthModel>(context).token).get(UrlConst.order_list, params: {'orderNo': widget.roomId});
    var item = response['pages']['records'][0];
    setState(() {
      state = item['state'].toString();
      uno = item['uno'].toString();
      getBtnText(state);
      orderInfos = [
        itemWidget('项目名称', item['projectName'].toString()),
        itemWidget('项目类型', item['projectTypeName'].toString()),
        const SizedBox(height: 10),
        Container(
          height: 0.5,
          color: Colors.grey,
        ),
        const SizedBox(height: 10),
        itemWidget('订单编号', item['orderNo'].toString()),
        itemWidget('创建时间', item['createTime'].toString()),
        itemWidget('护理师', item['serviceEmployeeName'] ?? ''),
        itemWidget('预约时间', item['serviceDate']==null?'':item['serviceDate'].toString()),
        itemWidget('预约门店', item['serviceStoreName']==null?'':item['serviceStoreName'].toString()),
        itemWidget('支付金额', item['singlePayAmount']==null?'':item['singlePayAmount'].toString()),
        itemWidget('订单状态', StateUtil.getStateName(item['state']),contentColor: Colors.green),
        itemWidget('支付状态', item['readyToPay']=='2'?'已支付':'未支付'),
        const SizedBox(height: 10),
        Container(
          height: 0.5,
          color: Colors.grey,
        ),
        SizedBox(height: 10,),
        itemWidget('用户编号', item['godNo'].toString()),
        itemWidget('用户电话', item['godPhone'] ?? ''),
      ];
    });
  }


  getBtnText(String state) {
    if(state == '4') {
      setState(() {
        btnText = '开始服务';
      });
    }
    if(state == '5') {
      setState(() {
        btnText = '完成服务';
      });
    }
  }

  Widget itemWidget(String title, String content,{Color? contentColor}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(title + ': ',style: TextStyle(fontSize: 14),),
        Text(content,style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold,color: contentColor==null?Colors.black:contentColor),),
      ],
    );
  }

}
